<template>
    <el-dialog v-model="open" width="600" destroy-on-close :title="diaTitle">
        <!-- 输入框 -->
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" style="max-width: 600px" label-width="auto"
            :label-position="labelPosition" :size="size">
            <el-form-item label="客服头像:" prop="avatar">
                <!-- 头像上传 -->
                <el-upload class="avatar-uploader" action="http://nocat.life:3011/images/upload"
                :show-file-list="false" :on-success="handleAvatarSuccess" >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                <Plus />
                </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="客服名称:" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入客服名称" />
            </el-form-item>
            <el-form-item label="手机号码:" prop="phone">
                <el-input placeholder="添加手机号码" />
            </el-form-item>
            <el-form-item label="登录账号:" prop="">
                <el-input placeholder="请输入登录账号" />
            </el-form-item>
            <el-form-item label="登录密码:" prop="">
                <el-input placeholder="请输入登录密码" />
            </el-form-item>
            <el-form-item label="确认密码:" prop="">
                <el-input placeholder="请输入确认密码" />
            </el-form-item>

            <el-form-item label="客服状态:" prop="state">
                <!-- 单选框 -->
                <template v-if="ruleForm.state == '1'">
                    <el-switch v-model="value" />
                </template>
                <template v-else>
                    <el-switch v-model="value2" />
                </template>
            </el-form-item>

            <!-- <el-form-item label="手机订单管理:" prop="state">
                <template #default="scope">
                    <el-switch v-model="value2" />
                </template>
            </el-form-item>
            <el-form-item label="订单通知:" prop="state">
                <template #default="scope">
                    <el-switch v-model="value2" />
                </template>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="open = false">取消</el-button>
                <el-button type="primary" @click="handOk">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import api from '../../api';
import { ElMessage } from 'element-plus'
import type { ComponentSize, FormProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
// 上传之前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const labelPosition = ref<FormProps['labelPosition']>('right')
const size = ref<ComponentSize>('default')
// 接受父组件的函数
const emit = defineEmits(["getServerData"])
// 接受父组件数据
// let { isShow, ruleForm } = defineProps(["isShow", "ruleForm"])
// let ruleForm=ref({})
// console.log(isShow, 55);


let open = ref(false)

interface RuleForm {
    _id: string,
    name: string,
    phone: string,
    avatar: string,
    state: number
}
const fileList = ref<UploadUserFile[]>([
    {
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    },
])
// const dialogImageUrl = ref('')
let ruleForm = ref({
    _id: "",
    name: "",
    date: "",
    avatar: "",
    state: "0",
})

// 状态
const value = ref(true)
const value2 = ref(false)
// 点击打开弹窗
function openDialog(data?: any) {
    // console.log(data);
    if (data) {
        ruleForm.value = {...data}
    }
    open.value = true
}
// 操作新增和修改
const handOk = () => {
    if (!ruleForm.value._id) {
        addServer()
    } else {
        updateServer()
    }
    open.value = false
}
// 点击确认添加客服
const addServer = async () => {
    // console.log( ruleForm.value);
    let {name,avatar,state,date}=ruleForm.value
    const res = await api.servers.add(
    {
       name,
       avatar,
       state,
       date
    }
    )
    if (res.code == 200) {
        // console.log(res);
        ElMessage({
            message: '配送员新增成功',
            type: 'success',
        })
        emit("getServerData")
        open.value = false
    } else {
        ElMessage.error(res.message)
    }
}
// 修改配送员信息
const updateServer = async () => {
    const res = await api.servers.update({
        _id: "",
        avatar: "",
        date: "",
        name: "",
        state: "",
    })
    console.log(res);

    if (res.code == 200) {
        ElMessage({
            message: '配送员修改成功',
            type: 'success',
        })
        emit("getServerData")
        open.value = false
    } else {
        ElMessage.error(res.message)
    }
}

const diaTitle = ref("")
//   关闭弹窗清空不需要再做了

// {deep:true})
//弹窗标题的变化
watch(() => ruleForm.value.name, () => {
    if (ruleForm.value._id) {
        diaTitle.value = "修改客服"
    } else {
        diaTitle.value = "添加客服"
        console.log(imageUrl.value);
        
    }
}, {
    immediate: true
})
// 定义表单的验证规则
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入分组名', trigger: 'blur' },
    ],
})
//   暴露方法
// defineExpose({
//     openDia
// })
defineExpose({
    openDialog
})
</script>
<style scoped></style>